package chpt05;

import java.util.Arrays;
import java.util.Comparator;

class PersonNameComparator implements Comparator<Person> {
	public int compare(Person p1, Person p2) {
		return p1.getName().compareTo(p2.getName());
	}
}

class PersonAgeComparator implements Comparator<Person> {
	public int compare(Person p1, Person p2) {
		return p1.getAge() - p2.getAge();
	}
}

public class ComparatorSortTest {
	public static void main(String[] args) {
		Person[] persons = new Person[4];
		persons[0] = new Person("Wang", 25);
		persons[1] = new Person("Bo", 30);
		persons[2] = new Person("Zheng", 20);
		persons[3] = new Person("Chen", 25);
		System.out.print("初始数据：");
		System.out.println(Arrays.toString(persons));
		System.out.print("姓名排序：");
		Arrays.sort(persons, new PersonNameComparator());
		System.out.println(Arrays.toString(persons));
		System.out.print("年龄排序：");
		Arrays.sort(persons, new PersonAgeComparator());
		System.out.println(Arrays.toString(persons));
		//sortByAnonymousClass(persons);
			
	}

	private static void sortByAnonymousClass(Person[] persons) {
		
		// 创建person数组的代码。
		// 使用匿名类实现对Person数组按姓名进行排序
		Arrays.sort(persons, new Comparator<Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				return p1.getName().compareTo(p2.getName());
			}
			
		});
		System.out.println();
		// 使用匿名类实现对Person数组按年龄进行排序
		Arrays.sort(persons, new Comparator<Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				return p1.getAge() - p2.getAge();
			}
		});
		
		System.out.println(Arrays.toString(persons));
		
	}
}
